import { defineStore } from 'pinia'
import { userApi } from '@/api'
import http from '@/api/http'

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
    token: null,
    isLoggedIn: false
  }),

  getters: {
    isAdmin: (state) => {
      return state.userInfo?.role === 'admin'
    },
    username: (state) => {
      return state.userInfo?.username || ''
    },
    userId: (state) => {
      return state.userInfo?.id || null
    }
  },

  actions: {
    // 登录
    async login(credentials) {
      try {
        const result = await userApi.login(credentials)
        this.token = result.token
        this.userInfo = result.user || result
        this.isLoggedIn = true
        
        // 设置HTTP客户端的token
        http.setToken(result.token)
        
        // 保存用户信息到localStorage
        localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
        
        return result
      } catch (error) {
        console.error('登录失败:', error)
        throw error
      }
    },

    // 注册
    async register(userData) {
      try {
        const result = await userApi.register(userData)
        return result
      } catch (error) {
        console.error('注册失败:', error)
        throw error
      }
    },

    // 获取当前用户信息
    async fetchCurrentUser() {
      try {
        const userInfo = await userApi.getCurrentUser()
        this.userInfo = userInfo
        // 保存用户信息到localStorage
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
        return userInfo
      } catch (error) {
        console.error('获取用户信息失败:', error)
        throw error
      }
    },

    // 登出
    async logout() {
      this.userInfo = null
      this.token = null
      this.isLoggedIn = false
      
      // 清除localStorage
      localStorage.removeItem('userInfo')
      localStorage.removeItem('token')
      
      // 清除HTTP客户端的token
      http.setToken(null)
    },

    // 检查登录状态
    checkAuth() {
      const token = localStorage.getItem('token')
      const userInfo = localStorage.getItem('userInfo')
      
      if (token && userInfo) {
        try {
          this.token = token
          this.userInfo = JSON.parse(userInfo)
          this.isLoggedIn = true
          http.setToken(token)
          
          // 尝试获取最新用户信息
          this.fetchCurrentUser().catch(() => {
            // 如果获取用户信息失败，可能token已过期，执行登出
            this.logout()
          })
        } catch (e) {
          console.error('解析用户信息失败:', e)
          this.logout()
        }
      }
    },

    // 更新用户信息
    updateUserInfo(userInfo) {
      this.userInfo = { ...this.userInfo, ...userInfo }
      // 更新localStorage
      localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
    },

    // 更新用户头像
    updateAvatar(avatarUrl) {
      if (this.userInfo) {
        this.userInfo.avatar = avatarUrl
        // 更新localStorage
        localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
      }
    }
  }
})
